package com.nofeng.wx.controller;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/ws/json") // 客户端连接地址
public class JsonWebSocket {
    private Session session;
    private static final CopyOnWriteArraySet<JsonWebSocket> connections = new CopyOnWriteArraySet<>();

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        connections.add(this);
        sendJsonResponse(); // 连接成功时立即发送JSON
    }

    private void sendJsonResponse() {
        try {
            String json = "{\"status\":\"connected\", \"message\":\"Welcome to WebSocket!\", \"timestamp\":" + System.currentTimeMillis() + "}";
            session.getBasicRemote().sendText(json); // 主动推送JSON
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose() {
        connections.remove(this);
    }

    @OnError
    public void onError(Throwable error) {
        error.printStackTrace();
    }
}